package engine.motionDetection;

import java.awt.Color;
import java.awt.image.BufferedImage;

/**
 * 
 * Tracking of the hand of the player
 * @author HINB
 *
 */
public class HandTracking {
	

	/* *********************************************************
	 * Static Methods
	 * ********************************************************* */
/**
 * track the position of the hand given an image, the average color and a margin
 * @param image the image to track the hand from
 * @param margin the margin to apply on the color average of the hand
 * @param average color average of the hand
 * @param low_margin low margin for the number of pixel detected
 * @param high_margin high margin for the number of pixel detected
 * @return the coordinates of the barycenter of the hand
 * -1 -1 if too few or too many matches
 */
	public static int[] track(BufferedImage image,int margin, Color average, int low_margin, int high_margin)
	{		
		System.out.println("engine.motionDetection : track");	
		
		int coord[] = {0,0};
		int count = 0;

		//get the size of the image
		int width = image.getWidth();
		int height = image.getHeight();
		
		for(int j=0; j<(height-1); j++)
		{
			for(int i=0; i<(width-1); i++)
			{	
				int rgb = image.getRGB(i, j);
				if((((rgb>>16) & 0xFF)>(average.getRed()-margin)&&
						((rgb>>16) & 0xFF)<(average.getRed()+margin))&&
						
						(((rgb>>8) & 0xFF)>(average.getGreen()-margin)&&
						((rgb>>8) & 0xFF)<(average.getGreen()+margin))&&
						
						((rgb & 0xFF)>(average.getBlue()-margin)&&
						(rgb & 0xFF)<(average.getBlue()+margin)))	{
					coord[0] = coord[0] + i;
					coord[1] = coord[1] + j;
					count++;
				}
			}
		}
		if(count>0){
			//compute the average
			coord[0] = (int) Math.floor(coord[0]/count);
			coord[1] = (int) Math.floor(coord[1]/count);
			
			//test for wrong detection (too many or too few points)
			if((count<low_margin)||(count>high_margin)){
				coord[0] = -1;
				coord[1] = -1;
			}
		}
		else{
			coord[0] = -1;
			coord[1] = -1;
		}
		
		//return the coordinates of the barycenter of the hand
		return coord;
	}
}
